package net.child.chess.gui;

import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageButton;
import net.child.chess.pieces.Piece;
import net.child.chess.utils.ChessDef;

public class SquareButton extends ImageButton
{
	public SquareButton(Context context, View.OnClickListener listener, Piece piece, int position, int width, ButtonUsage usage)
	{
		super(context);
	
		mPiece = piece;
		mPosition = position;
		mButtonUsage = usage;
		
		//	Set the piece image on the square button if needed.
		if(piece != null)
		{
			setImageResource(piece.imageId());
		}
		
		setLayoutParams(new GridView.LayoutParams(width, width));
		setOnClickListener(listener);
		
		//	determine on square color, white or "saddle brown"?
		if((position/ChessDef.BOARD_NUM_COLUMNS) % 2 == 0)
		{
			mOriginalBackgroundColor = (position % 2 == 0) ? Color.WHITE :Color.rgb(139,69,19); 
		}
		else
		{
			mOriginalBackgroundColor = (position % 2 == 0) ? Color.rgb(139,69,19) : Color.WHITE;
		}
		setBackgroundColor(mOriginalBackgroundColor);
		mBackgroundColorAttribute = BackgroundColorAttribute.ORIGINAL_COLOR;
	}
	
	// 	return the piece that associated to the button.
	//	hold null if the square is empty.
	public Piece piece()
	{
		return mPiece;
	}
	
	//	called when a new piece was move to the current square.
	public void piece(Piece p)
	{
		mPiece = p;
		if(mPiece == null)
		{
			setImageDrawable(null);
		}
		else
		{
			setImageResource(mPiece.imageId());
		}
		invalidate();
	}
	
	public int position()
	{
		return mPosition;
	}
	
	//	The following attributes control the background colors.
	public enum BackgroundColorAttribute
	{
		VALID_MOVEMONT_COLOR,
		ORIGINAL_COLOR
	};
	void setBackgroundColorAttribute(BackgroundColorAttribute attribute)
	{
		if(attribute != mBackgroundColorAttribute)
		{
			mBackgroundColorAttribute = attribute;
			if(mBackgroundColorAttribute == BackgroundColorAttribute.VALID_MOVEMONT_COLOR)
			{
				setBackgroundColor(Color.YELLOW);
			}
			else // ORIGINAL_COLOR
			{
				setBackgroundColor(mOriginalBackgroundColor);
			}
			invalidate();
		}
	}
	
	public enum ButtonUsage
	{
		GAME_BUTTON,
		PROMOTION_BUTTON
	};
	public ButtonUsage usage()
	{
		return mButtonUsage;
	}
	
	private Piece mPiece;
	private int mPosition;
	private BackgroundColorAttribute mBackgroundColorAttribute;
	private int mOriginalBackgroundColor;
	ButtonUsage mButtonUsage;
}
